'''
Author: newsun
Date: 2022-01-07 20:30:34
LastEditTime: 2022-01-11 20:52:53
LastEditors: newsun-HP-Pavilion-Gaming-Laptop-15-dk0xxx
Description: 反陀螺
FilePath: /Vision_bak/tool/curve_plot/anti-spin.py
'''
import numpy as np
import matplotlib.pyplot as plt
from sys import argv

if __name__ == "__main__":
    sampling_num = 30
    boundary = 320
    data_r = np.loadtxt("tool/curve_plot/1.txt", delimiter=',')
    
    plt.ion()  #打开交互模式
    for line in range(data_r.shape[0]):
        is_spin = 1#是否在陀螺
        if line < 100: 
            continue
        data = data_r[line - 100:line,0]
        # data_n = data.copy()
        
        # 数据归一化
        # for i in range(data.shape[0]):
        #     min_data = np.min(data)
        #     max_data = np.max(data)
        #     data_n[i] = (data[i] - min_data)/(max_data-min_data)
        
        # plt.figure(1)
        # plt.title('x_position(N)')
        # plt.scatter(np.arange(len(data_n)),data_n)
        # plt.show()
        
        data_v = data.copy()
        v_points = []#2i为跳变点的index，2i+1为差分值
        for index in range(1,data.shape[0]):
            data_v[index] = data[index] - data[index-1]
            if(abs(data_v[index]) > 150): 
                v_points.append(index)
                v_points.append(data_v[index])
        # print(v_points)
        if len(v_points) < 8:  ## 跳变点太少的不要
            is_spin = 0
            # continue
        for i in range(2,len(v_points),2):
            if abs(v_points[i + 1] - v_points[i - 1]) > 80 or abs(v_points[i] - v_points[i - 2]) > 20 \
                or abs(v_points[i] - v_points[i - 2]) < 3 :#差分值差距不能超过80，相邻跳变点相隔不能超过20
                is_spin = 0
                # continue
        
        #中间递增的判断
        mid_avg= 0
        for i in range(2,len(v_points),2):
            mid_points = data[v_points[i - 2] + 1:v_points[i]]
            s = 0
            if i == len(v_points) - 2:
                mid_avg = np.average(mid_points)
            for j in range(1,len(mid_points)):
                if mid_points[j] > mid_points[j - 1]:
                    s = s + 1
            s = s / len(mid_points)
            if(s < 0.75):
                is_spin = 0
        
        print(mid_avg)
        ## 选取最后一次递增为击打中心点
        #动态画图
        plt.figure(0)
        plt.title('x_position')
        if is_spin == 1:
            plt.scatter(np.arange(len(data)),data,c = 'r')
        else:
            plt.scatter(np.arange(len(data)),data,c = 'b')
        plt.show()
        plt.pause(0.0001)
        plt.clf()  #清除图像
